#!/bin/bash
set -e

echo "📚 PRD 文档导出脚本 - mdBook"
echo "工作目录：$(pwd)"

# 检查 mdBook 是否已安装
if command -v mdbook &> /dev/null; then
  echo "✅ mdBook 已安装：$(mdbook --version)"
else
  echo "⚠️  mdBook 未安装，正在安装..."
  # macOS 用户首选 Homebrew，次选 cargo
  if command -v brew &> /dev/null; then
    brew install mdbook
  elif command -v cargo &> /dev/null; then
    cargo install mdbook
  else
    echo "❌ 未找到 Homebrew 或 cargo，请手动安装 mdBook："
    echo "   brew install mdbook"
    echo "   或访问：https://github.com/rust-lang/mdBook#installation"
    exit 1
  fi
fi

# 检查并创建输出目录
mkdir -p book

# 构建 HTML
echo "🔨 构建 HTML 文档..."
mdbook build

echo "✅ 文档构建完成！"
echo "📁 HTML 文档位置：$(pwd)/book/"
echo "🌐 在浏览器中打开：file://$(pwd)/book/index.html"

# 尝试在默认浏览器中打开
if [[ "$OSTYPE" == "darwin"* ]]; then
  open "$(pwd)/book/index.html"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
  xdg-open "$(pwd)/book/index.html"
fi

echo "📋 导出选项："
echo "  - HTML: $(pwd)/book/"
echo "  - PDF: 需安装 weasyprint（pip install weasyprint）后执行 mdbook build"
echo "  - 自定义样式：编辑 src/style.css"